package com.xxx.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.mall.converter.AttrConverter;
import com.xxx.mall.dto.AttrValueDTO;
import com.xxx.mall.exception.MallException;
import com.xxx.mall.mapper.AttrValueMapper;
import com.xxx.mall.model.AttrValue;
import com.xxx.mall.service.AttrValueService;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 属性值信息 服务实现类
 * </p>
 *
 * @author 邢晨旭
 * @since 2023-11-23
 */
@Service
public class AttrValueServiceImpl extends ServiceImpl<AttrValueMapper, AttrValue> implements AttrValueService {

    @Resource
    AttrConverter attrConverter;

    @Override
    public void saveByAttrId(Long attrId, List<AttrValueDTO> attrValues) {
        if (CollUtil.isEmpty(attrValues)) {
            throw new MallException("至少添加一个属性值");
        }
        List<AttrValue> attrValueList = attrConverter.toAttrValue(attrValues);
        attrValueList.forEach(attrValue -> attrValue.setAttrId(attrId));
        AttrValueService proxy = (AttrValueService) AopContext.currentProxy();
        proxy.saveBatch(attrValueList);
    }

    @Override
    public void updateByAttrId(Long attrId, List<AttrValueDTO> attrValues) {
        if(CollUtil.isEmpty(attrValues)){
            throw new MallException("至少添加一个属性值");
        }
        AttrValueService proxy = (AttrValueService) AopContext.currentProxy();
        List<AttrValue> dbValues = baseMapper.queryValueByAttrId(attrId);
        List<AttrValue> addAttrValue = new ArrayList<>();
        List<AttrValue> updateAttrValue = new ArrayList<>();
        List<Long> deleteAttrValue = dbValues.stream().map(AttrValue::getAttrValueId).collect(Collectors.toList());
        attrValues.forEach(item -> {
            item.setAttrId(attrId);
            if (item.getAttrValueId() == null) {
                addAttrValue.add(attrConverter.toAttrValue(item));
            } else {
                updateAttrValue.add(attrConverter.toAttrValue(item));
                deleteAttrValue.remove(item.getAttrValueId());
            }
        });
        if (CollUtil.isNotEmpty(addAttrValue)) {
            //新增
            proxy.saveBatch(addAttrValue);
        }
        if (CollUtil.isNotEmpty(updateAttrValue)) {
            //修改
            proxy.updateBatchById(updateAttrValue);
        }
        if (CollUtil.isNotEmpty(deleteAttrValue)) {
            //删除
            proxy.deleteByIds(deleteAttrValue);
        }
    }

    @Override
    public void deleteByIds(List<Long> deleteAttrValue) {
        baseMapper.removeByIds(deleteAttrValue);
    }
}
